<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
      <el-form-item label="里程碑名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入里程碑名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="里程碑状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择里程碑状态" clearable>
          <el-option
            v-for="item in projectStatusList"
            :key="item.dictValue"
            :label="item.dictLabel"
            :value="item.dictValue"
            :disabled="item.disabled"
          />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="info"-->
<!--          plain-->
<!--          icon="el-icon-sort"-->
<!--          size="mini"-->
<!--          @click="toggleExpandAll"-->
<!--        >展开/折叠</el-button>-->
<!--      </el-col>-->
      <el-row :gutter="10" class="mb8">
      <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport">导出</el-button>
      </el-row>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
      v-if="refreshTable"
      v-loading="loading"
      :data="deptList"
      :default-expand-all="isExpandAll"
    >
      <el-table-column prop="name" label="里程碑名称" width="150" align="center"></el-table-column>

      <el-table-column prop="status" align="center" label="里程碑状态" width="120">
        <template slot-scope="scope">
          <el-tag :type="tags[scope.row.status].type">{{tags[scope.row.status].label}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="endTime" align="center" label="截至时间" width="200">
        <template slot-scope="scope">
          <span >{{ scope.row.endTime }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="tasksList" align="center" label="任务列表" width="200">
        <template slot-scope="scope">
          <div v-for="item in scope.row.tasksList">
            <el-tag>{{item.name}}</el-tag>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="remark" align="center" label="描述" width="200">
        <template slot-scope="scope">
          <span >{{ scope.row.remark }}</span>
        </template>
      </el-table-column>
<!--      <里程碑-column label="创建时间" align="center" prop="createTime" width="200">-->
<!--        <template slot-scope="scope">-->
<!--          <span>{{ parseTime(scope.row.createTime) }}</span>-->
<!--        </template>-->
<!--      </el-table-column>-->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改里程碑对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="750px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="项目" prop="projectId">
              <el-select v-model="form.projectId" placeholder="请选择项目" clearable @change="chooseLeader">
                <el-option
                  v-for="item in projectList"
                  :key="item.deptId"
                  :label="item.deptName"
                  :value="item.deptId"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="名称" prop="name" >
              <el-input v-model="form.name" placeholder="请输入里程碑名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="状态">
              <el-select v-model="form.status" placeholder="请选择里程碑状态">
                <el-option
                  v-for="item in projectStatusList"
                  :key="item.dictValue"
                  :label="item.dictLabel"
                  :value="item.dictValue"
                  :disabled="item.disabled"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="任务选择">
              <el-select
                v-model="form.tasksList"
                multiple
                filterable
                @change="handleChange"
                placeholder=""
                style="width: 240px"
              >
                <el-option
                  v-for="item in tasks"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-form-item label="截至时间" prop="endTime">
            <el-date-picker
              v-model="form.endTime"
              type="datetime"
              value-format="yyyy-MM-dd HH:mm:ss"
              format="yyyy-MM-dd HH:mm:ss"
              :shortcuts="shortcuts"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              :style="{width:'100%'}"
            />
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="描述" prop="remark" label-width="80px">
            <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"  maxlength="200"/>
          </el-form-item>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listDept,
  getDept,
  delDept,
  addDept,
  updateDept,
  listDeptExcludeChild,
  getLeader,
  listMilestone,
  listProject,
  listTasks, getTaskMilestone
} from "@/api/system/milestone";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "milestone",
  dicts: ['sys_normal_disable'],
  components: { Treeselect },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 表格树数据
      deptList: [],
      // 里程碑树选项
      deptOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否展开，默认全部展开
      isExpandAll: true,
      // 重新渲染表格状态
      refreshTable: true,
      // 查询参数
      queryParams: {
        deptName: undefined,
        status: undefined,
        leader: undefined,
      },
      //标签显示
      tags:[
        {
          label:'未进行',
          type:'info',
        },
        {
          label:'进行中',
          type:'primary',
        },
        {
          label:'已延期',
          type:'warning',
        },
        {
          label:'已完成',
          type:'success',
        },
      ],
      //优先级标签显示
      levelTags:[
        {
          label:'低',
          type:'info',
        },
        {
          label:'中',
          type:'primary',
        },
        {
          label:'高',
          type:'warning',
        }
      ],
      //里程碑状态字典
      projectStatusList: [],
      //项目的列表
      projectList:[],
      //任务列表
      tasks:[],
      // 表单参数
      form: {
        deptId: undefined,
        parentId: undefined,
        deptName: undefined,
        orderNum: undefined,
        leader: undefined,
        phone: undefined,
        email: undefined,
        status: "0",
        remark: undefined,
        time: undefined,
        beforeList:[],
      },
      // 表单校验
      rules: {
        name: [
          { required: true, message: "里程碑名称不能为空", trigger: "blur" }
        ],
        endTime: [
          { required: true, message: "截至时间不能为空", trigger: "blur" }
        ],
        level: [
          { required: true, message: "优先级不能为空", trigger: "blur" }
        ],
        //负责人
        leader: [
          { required: true, message: "负责人不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
    this.getDicts("milestone_status").then(res => {
      this.projectStatusList = res.data;
    });
  },
  methods: {
    /** 查询里程碑列表 */
    getList() {
      this.loading = true;
      listDept(this.queryParams).then(response => {
        this.deptList = response.rows;
        this.loading = false;
      });
    },
    /** 导出功能 */
    handleExport(){
      this.download('/system/milestone/export',this.queryParams, `里程碑数据${new Date().getTime()}.xlsx`)
    },
    //选择事件
    handleChange(value){
      console.log("选中",value)
      //调用任务和里程碑判断 - 任务和里程碑只能是一对一
      if(value && value.length>0){
        //有问题后端会报错
        getTaskMilestone(value).catch(()=>{
          //清空
          this.form.tasksList = [];
        })
      }
    },
    /** 转换里程碑数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.deptId,
        label: node.deptName,
        children: node.children
      };
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        deptId: undefined,
        parentId: undefined,
        deptName: undefined,
        orderNum: undefined,
        leader: undefined,
        phone: undefined,
        email: undefined,
        status: "0",
        remark: undefined,
        time: undefined,
        milestoneId:undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.reset();
      this.open = true;
      this.title = "添加里程碑";
      listProject().then(response => {
        console.log('项目',response)
        this.projectList = response.data;
        //过滤项目列表中parentId为0的
        this.projectList = this.projectList.filter(item => item.parentId !== 0);
      });
      listTasks().then(res => {
        this.tasks = res.rows;
      })
    },
    /** 展开/折叠操作 */
    toggleExpandAll() {
      this.refreshTable = false;
      this.isExpandAll = !this.isExpandAll;
      this.$nextTick(() => {
        this.refreshTable = true;
      });
    },
    /** 选择负责人 */
    chooseLeader(leaderUsername){
      //从负责人列表中获取对应的信息
      var leader = this.projectPersonList.find(item => item.userName === leaderUsername);
      //级联更新
      this.form.email = leader.email;
      this.form.phone = leader.phonenumber;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      getDept(row.id).then(response => {
        this.form = response.data;
        this.form.time = [row.planStartTime,row.planEndTime];
        var taskIds = [];
        if(this.form.tasksList && this.form.tasksList.length>0){
          for (let tasksListKey in this.form.tasksList) {
            taskIds.push(this.form.tasksList[tasksListKey].id)
          }
          this.form.tasksList = taskIds;
        }
        // 过滤掉未找到的项
        this.open = true;
        this.title = "修改里程碑";
        // listDeptExcludeChild(row.deptId).then(response => {
        //   this.deptOptions = this.handleTree(response.data, "deptId");
        //   if (this.deptOptions.length == 0) {
        //     const noResultsOptions = { deptId: this.form.parentId, deptName: this.form.parentName, children: [] };
        //     this.deptOptions.push(noResultsOptions);
        //   }
        // });
        listProject().then(response => {
          console.log('项目',response)
          this.projectList = response.data;
          //过滤项目列表中parentId为0的
          this.projectPersonList = this.projectList.filter(item => item.parentId !== 0);
        });
        listTasks().then(res => {
          this.tasks = res.rows;
        })
      });
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          //修改时间
          if(this.form.time){
            this.form.planStartTime = this.form.time[0];
            this.form.planEndTime = this.form.time[1];
          }

          //将任务列表添加上去
          if(this.form.tasksList && this.form.tasksList.length>0){
            var list = [];
            for (let i = 0; i < this.form.tasksList.length; i++) {
              //通过id取出来
              for (let j = 0; j < this.tasks.length; j++) {
                if(this.form.tasksList[i] === this.tasks[j].id){
                  list.push(this.tasks[j]);
                  break;
                }
              }
            }
            this.form.tasksList = list;
          }

          if (this.form.id != undefined) {
            updateDept(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {

            addDept(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$modal.confirm('是否确认删除名称为"' + row.name + '"的数据项？').then(function() {
        return delDept(row.id);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    }
  }
};
</script>
